package com.atom.module.coroutine.dispatcher

import kotlin.coroutines.AbstractCoroutineContextElement
import kotlin.coroutines.Continuation
import kotlin.coroutines.ContinuationInterceptor

// 分发者
interface Dispatcher {
    fun dispatch(block: () -> Unit)
}

// 分发的 重要的实现了挂起和重启的概念
// 这个是个包装 , 内部包含主要的 Continuation 和 分发Dispatcher 类 并且实现了 Continuation类型
private class DispatchedContinuation<T>(val delegate: Continuation<T>, val dispatcher: Dispatcher) :
    Continuation<T> {
    override val context = delegate.context
    override fun resumeWith(result: Result<T>) {
        dispatcher.dispatch {
            delegate.resumeWith(result)
        }
    }
}

// 分发上下文 ,
open class DispatcherContext(private val dispatcher: Dispatcher) : AbstractCoroutineContextElement(ContinuationInterceptor.Key), ContinuationInterceptor {
    override fun <T> interceptContinuation(continuation: Continuation<T>): Continuation<T> {
        return DispatchedContinuation(continuation, dispatcher)
    }
}